﻿using System;
using System.Net;
using System.Xml.Linq;
using PureMVC.Interfaces;
using PureMVC.Patterns;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.IO;

namespace GameEngine.Model
{
    /// <summary>
    /// Há uma acção no jogo essa acção é enviada para o servidor
    /// Servidor constantemente a enviar info de alterações
    /// (?) estado para saber se já chegou a um certo estado
    /// </summary>
    abstract public class DataProxy : Proxy, IDataProxy
    {
        //static String MYNAME = "DataProxy";
        //static DataProxy instance = null;
        
        public string ServerUrl
        {
            get
            {
                String url = "http://localhost:8080/MMOG";
                url += "/data.php";
                /*switch (ApplicationFacade.Instance().CurrentView)
                {
                    case ApplicationFacade.View.Village:
                        url += "/village.php";
                        break;
                    case ApplicationFacade.View.County:
                        url += "/county.php";
                        break;
                    case ApplicationFacade.View.Continental:
                        url += "/continental.php";
                        break;
                }*/
                //url += "?userId=" + ApplicationFacade.Instance().User+"&";
                return url;
            }
        }
        
        Uri Uri {
            get { return new Uri(ServerUrl);  }
        }

        public DataProxy(string Name, object VO) : base(Name,VO){ 
        
        }

       // //new Uri(remoteUrl, UriKind.Absolute)
       //// protected DataProxy()
       // //    : base(MYNAME)
       // //{
       //     //WebClient remoteData = new WebClient();
       //     //client.DownloadProgressChanged += changeCallback;
       //     //remoteData.DownloadStringCompleted += newRemoteData;
       //     //remoteData.DownloadStringAsync(Uri);
            
       //     /*
       //         * MMOG.PHPServices.SimpleService svc = new SimpleService();
       //     string s = svc.ProcessSimpleType("steve");
       //     MessageBox.Show(s);

       //     //serverhelloPortTypeClient svc = new MMOG.PHPServices2.serverhelloPortTypeClient();
       //     //string s = svc.("steve");
       //     // new ASPService.Service1Soap().
       //     //MessageBox.Show(s);
       //         */
       //     /*
       //     System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
       //     req.Proxy = new System.Net.WebProxy(ProxyString, true);

       //     req.ContentType = "application/x-www-form-urlencoded";
       //     req.Method = "POST";

       //     byte [] bytes = System.Text.Encoding.ASCII.GetBytes(Parameters);
       //     req.ContentLength = bytes.Length;

       //     System.IO.Stream os = req.GetRequestStream ();
       //     os.Write (bytes, 0, bytes.Length); 
       //     os.Close ();

       //     System.Net.WebResponse resp = req.GetResponse();
       //     if (resp== null) return null;

       //     System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
       //     return sr.ReadToEnd().Trim();
       //     */
       //     //TODO s+o pode ligar no server
       //     /*
       //     string MyConString = "server=localhost;user id=user;Password=conhecido;persist security info=True;database=silverlight";
       //     SqlConnection connection = new SqlConnection(MyConString); 
       //     MySqlCommand command = connection.CreateCommand(); 
       //     MySqlDataReader Reader; 
       //     command.CommandText = "select * from mycustomers"; connection.Open(); 
       //     Reader = command.ExecuteReader(); 
       //     while (Reader.Read()) { 
       //         string thisrow = ""; 
       //         for (int i = 0; i < Reader.FieldCount; i++)						
       //             thisrow += Reader.GetValue(i).ToString() + ","; 
       //         //listBox1.Items.Add(thisrow); 
       //     } 
       //     connection.Close();
       //         * */
       // //}

       // //public static DataProxy Instance{
       // //    get{
       // //        if (instance == null)
       // //        {
       // //            instance = new DataProxy();
       // //        }
       // //        return instance;
       // //    }
       // //}

        /*        public void sendCommand(string command, string args, callback) {
            PHPServiceReferenceTest2.serverhelloPortTypeClient teste2 = new PHPServiceReferenceTest2.serverhelloPortTypeClient(
            teste2.helloCompleted += new EventHandler<PHPServiceReferenceTest2.helloCompletedEventArgs>(
                delegate(object o, PHPServiceReferenceTest2.helloCompletedEventArgs args)
                {
                    if (args.Error == null)
                    {
                        MessageBox.Show(args.Result);
                    }
                    else
                    {
                        XDocument xmlResult = XDocument.Parse(args.Result);
                        List<ItemVOParameters> items = parseXML(xmlResult);
                        foreach (ItemVOParameters item in items)
                        {
                            String proxyName = ItemDataProxy.CreateName(new ItemVO(item.Id, item.Type));
                            ((ItemDataProxy)Facade.RetrieveProxy(proxyName)).OnUpdateData(item.Parameters);
                        }
                    }
                });
            teste2.helloAsync(xml.ToString());
        }*/

        /*private void newRemoteData(object sender, DownloadStringCompletedEventArgs e)
        {
            //select alteracoes from pagina onde estou
            XElement xml = XElement.Parse(e.Result);

            foreach (XElement node in xml.ElementsAfterSelf()) {
                switch (node.Name.LocalName) { 
                    case ("TODO"):

                        break;
                }
            }
            
            remoteData.DownloadStringAsync(Uri);
        }*/

        /*public void SendData(List<ItemVOParameters> items)
        {
            sendByWS(createXML(items));
        }*/

        private void sendByWS(XDocument xml)
        {
            //BasicHttpBinding binding = new BasicHttpBinding();
            //PHPServiceReferenceTest2.serverhelloPortTypeClient teste2 = new PHPServiceReferenceTest2.serverhelloPortTypeClient(
            /*binding,new EndpointAddress("http://localhost:8080/MMOG/server2.php")*///);
            /*teste2.helloCompleted += new EventHandler<PHPServiceReferenceTest2.helloCompletedEventArgs>(
                delegate(object o, PHPServiceReferenceTest2.helloCompletedEventArgs args)
                {
                    if (args.Error == null)
                    {
                        MessageBox.Show(args.Result);
                    }
                    else
                    {
                        XDocument xmlResult = XDocument.Parse(args.Result);
                        List<ItemVOParameters> items = parseXML(xmlResult);
                        foreach (ItemVOParameters item in items) {
                            String proxyName = ThingDataProxy.CreateName(new ItemVO(item.Id, item.Type));
                            //((ItemDataProxy)Facade.RetrieveProxy(proxyName)).OnUpdateData(item.Parameters);
                        }
                    }
                });
            teste2.helloAsync(xml.ToString());*/
        }

        private void SendByHTTP(XElement xml, String notificationName, String notificationType)
        {
            WebClient sendData = new WebClient();
            //sendData.Headers["Content-Type"] = "application/x-www-form-urlencoded"; 
           // sendData.UploadProgressChanged += OnProgress;
           // sendData.UploadStringCompleted += OnCompleted;
            sendData.UploadStringAsync(Uri, "" /*"data="+xml.ToString()*/);
            SendNotification(notificationName, null, notificationType);
        }

        public XElement RetrieveData(XElement command)
        {
            /*StreamReader
            WebRequest we = new WebResponse(
            System.Net.WebRequest/WebResponse to create stream from the
remote XML document
  - Use StreamReader to get the string content
  - Then use XMLDocument.LoadXML to parse the string. 
            throw new NotImplementedException();*/
            return null;
        }

       //abstract public string Serialize();

        //private XDocument createXML(List<ItemVOParameters> items)
        //{
        //    XDocument doc = new XDocument();
        //    XElement itemsNode = new XElement("items");
        //    foreach (ItemVOParameters item in items)
        //    {
        //        XElement itemNode = new XElement("item");
        //        itemNode.Add(new XElement("type", item.Type));
        //        itemNode.Add(new XElement("id", item.Id));
        //        XElement parametersNode = new XElement("parameters");
        //        foreach (Parameter parameter in item.Parameters)
        //        {
        //            XElement parameterNode = new XElement("parameter");
        //            parameterNode.Add(new XElement("name", parameter.Name));
        //            parameterNode.Add(new XElement("value",parameter.Value));
        //            parametersNode.Add(parameterNode);
        //        }
        //        itemNode.Add(parametersNode);
        //        itemsNode.Add(itemNode);
        //    }
        //    doc.Add(items);
        //    return doc;
        //}

        //private List<ItemVOParameters> parseXML(XDocument xml)
        //{
        //    List<ItemVOParameters> result = new List<ItemVOParameters>();
        //    foreach (XElement itemNode in xml.Elements("items"))
        //    {
        //        int id = int.Parse(itemNode.Element("id").Value.ToString());
        //        String type = itemNode.Element("type").Value.ToString();
        //        List<Parameter> parameters = new List<Parameter>();
        //        foreach (XElement parameter in itemNode.Elements("Parameters"))
        //        {
        //            String name = parameter.Element("name").Value.ToString();
        //            String value = parameter.Element("value").Value.ToString();
        //            parameters.Add(new Parameter(name, value));
        //        }
        //        result.Add(new ItemVOParameters(new ItemVO(id, type), parameters));
        //    }
        //    return result;
        //}
    }
}
